package util;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class jdbcUtil {
	static String url="jdbc:mysql://localhost:3306/mybase?useUnicode=true&characterEncoding=utf-8";
	static String username="root";
	static String password="root";
	static {
		
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	public static void  close(Connection con,PreparedStatement p) throws SQLException {
		if(con!=null)con.close();
		if(p!=null)p.close();
	}
	public static void close(Connection con,PreparedStatement p,ResultSet rs) throws SQLException {
		if(rs!=null)rs.close();
		close(con,p);
	}
	public static int update(String sql,Object...array) {

		Connection con=null;
		PreparedStatement p=null;
		try {
			int jie=0;
			con=DriverManager.getConnection(url,username,password);
			p=con.prepareStatement(sql);
			if(array!=null) {
				for(int i=0;i<array.length;i++) {
					p.setObject(i+1,array[i]);
				}
			}
			jie=p.executeUpdate();
			return jie;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			try {
				close(con,p);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		return 0;
	}
	//数据库中的smallint 对应java中的Integer(或者int)
	public static <T> List<T> select(Class<T> cls,String sql,Object...array){
		Connection con =null;
		PreparedStatement p=null;
		ResultSet rs=null;
		List<T> list=new ArrayList<T>();
		try {
			con=DriverManager.getConnection(url,username,password);
			p=con.prepareStatement(sql);
			if(array!=null) {
				for(int i=0;i<array.length;i++) {
					p.setObject(i+1,array[i]);
				}
			}
			rs=p.executeQuery();
			while(rs.next()) {
				//newInstance() 调用类的无参构造方法。
				T t=cls.newInstance();
				//获取该类的所有属性，每个属性都会封装到Field对象中
				Field[] field =cls.getDeclaredFields();
				for(Field f:field) {
					//打开权限
					f.setAccessible(true);
//					try {
//						f.set(t,rs.getObject(f.getName()));
//					}catch(Exception e) {}
					
					//要求类中属性名跟数据库字段名完全一致！！！
					//如果不一致，1、可以使用sql语法的取别名as username as name 2、使用注解
					//利用Field对象的set()方法赋值
					f.set(t,rs.getObject(f.getName()));
				}
				list.add(t);	
			}
			return list;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			try {
				close(con,p,rs);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return null;
	}
	
	

}
